class Redis{
    private _sub:any={};
    private _channels:any=[];
    private _redis;
    private _config:any;
    constructor(Host="127.0.0.1",Port=6379,PWD:any=false,DB=0){
        let redis = require('ioredis');
        this._config ={
            host:Host,port:Port,
            db:DB,
        };
        if("string" == typeof PWD && PWD.length>0){
            this._config.password=PWD;
        }
        this._redis = new redis(this._config)
    };

    /**
     * 发布
     * @param channel
     * @param message
     */
    public publish=function (channel,message) {
        this._redis.publish(channel,"string" == typeof message?message:JSON.stringify(message))
    };
    /**
     * 订阅
     * @param channel
     * @param {Function} cb
     */
    public subscribe=function (channel) {
        if(!this._sub[channel]){
            let redis = require('ioredis');
            this._sub[channel] = new redis(this._config)
        }
        this._sub[channel].subscribe(channel,function (err,count) {

        });
        this._sub[channel].on('message',(pattern,channel,message)=> {
            try{
                var that = this;
                let json = JSON.parse(message);
                if(json.i&&json.i.length>2){
                    let C,A,i=json.i.split('/')
                    if(i.length==2) {
                        C = i[0];
                        A = i[1];
                        if("string"===typeof json.d && json.d.length>0){
                            json.d = JSON.parse(json.d);
                        }
                        let req={
                            body:json.d,
                            query:{
                                A:A,C:C,
                            },
                            params:{
                                A:A,C:C,
                            },
                            session:{
                                destroy:function(){}
                            }
                        },rep={
                            send:function (data,status=200) {
                                that._redis.publish("r_"+channel,{
                                    i:json.i,
                                    t:json.t,
                                    d:JSON.stringify(data),
                                    c:status
                                })
                            }
                        }
                        Server.onRequest(req,rep,function () {
                            
                        });
                    }
                }
            }catch (e){

            }
        });
    };
    /**
     * redis从获取请求数据
     * @param channel
     */
    public command=function (channel) {
        this.subscribe(channel,function (err,count) {
            
        })
    }
}
exports.Redis=Redis;